package com.glory.dgcpcpda.activity.mfg;

import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.MaterialBoxBindingAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.entity.BinInfoEntity;
import com.glory.dgcpcpda.entity.ChangeShiftEntity;
import com.glory.dgcpcpda.entity.EqpInfoEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.MerterialBoxBindingEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: ShiftExchangeTestActivity
 * Author: XJH
 * Date: 2021/6/24 15:58
 * Description:
 * History:
 */
public class MaterialBoxBindingActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etMaterialBox)
    FreeUI_ClearEditText etMaterialBox;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.list_tv5)
    TextView listTv5;
    @BindView(R.id.list_tv6)
    TextView listTv6;
    @BindView(R.id.list_tv7)
    TextView listTv7;
    @BindView(R.id.tvClear)
    TextView tvClear;
    @BindView(R.id.list_tv8)
    TextView listTv8;
    @BindView(R.id.list_btn)
    Button listBtn;
    @BindView(R.id.rvLotInfoList)
    RecyclerView rvLotInfoList;
    @BindView(R.id.llMain)
    LinearLayout llMain;

    private MaterialBoxBindingAdapter mMaterialBoxBindingAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_material_box_binding;
    }

    @Override
    protected void initView() {
        tvTitle.setText("料盒绑定");
        setMainLayout(llMain);
        listTv1.setText("序号");
        listTv2.setText("批次号");
        listTv3.setText("料盒号");
        listTv1.setVisibility(View.VISIBLE);
        listTv2.setVisibility(View.VISIBLE);
        listTv3.setVisibility(View.VISIBLE);
        listTv4.setVisibility(View.GONE);
        listTv5.setVisibility(View.GONE);
        listTv6.setVisibility(View.GONE);
        listTv7.setVisibility(View.GONE);
        listTv8.setVisibility(View.GONE);
        listBtn.setVisibility(View.VISIBLE);
        initRecyclerView(rvLotInfoList,this);
        tvBaseSubmit.setText("提交");
        mMaterialBoxBindingAdapter = new MaterialBoxBindingAdapter(null);
        rvLotInfoList.setAdapter(mMaterialBoxBindingAdapter);

        initEdit(etLot, s -> {
            //获取lot信息
            LotUtils.searchLotInfo(MaterialBoxBindingActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    if(!response.getLOT().getSTEPNAME().equals("A6000")
                            &&!response.getLOT().getSTEPNAME().equals("A6030")
                            &&!response.getLOT().getSTEPNAME().equals("A9025")){
                        showConfirmDialog("非电镀工序不允许使用该功能!");
                        etLot.setText("");
                        return;
                    }
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t,"LOTQUERY");
                }

            });
        });

        initEdit(etMaterialBox, s ->{
            etMaterialBox.setFocusable(true);
            etMaterialBox.requestFocus();
            if (getText(etLot).equals("")) {
                showToast("批次号不能为空，请检查", false);
                return;
            }
            if(mMaterialBoxBindingAdapter.getData().size()>34){
                showToast("批次列表数量不能超过20", false);
                return;
            }
            for (ChangeShiftEntity.ChangeShift data : mMaterialBoxBindingAdapter.getData()){
                if (data.getMATERIALBOX().equals(s)) {
                    showToast("当前载具"+s+"已添加到载具列表中", false);
                    return;
                }
            }
            LotUtils.checkCarrier(MaterialBoxBindingActivity.this,getText(etLot),s, getSupportFragmentManager(), new LotUtils.netCallback<Object>() {
                @Override
                public void onSuccess(Object response) {
                    ChangeShiftEntity.ChangeShift changeShift = new ChangeShiftEntity.ChangeShift();
                    changeShift.setLOTID(getText(etLot));
                    changeShift.setMATERIALBOX(s);
                    mMaterialBoxBindingAdapter.addData(changeShift);
                    clearContent();
                    etLot.setFocusable(true);
                    etLot.requestFocus();
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "CHECKCARRIER");
                }
            });
        });
    }

    @Override
    protected void initData() {
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @OnClick({R.id.tvBaseSubmit,R.id.list_btn,R.id.tvClear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                if(mMaterialBoxBindingAdapter.getData().size()<=0){
                    showToast("批次列表不能为空", false);
                    return;
                }
                FreeUI_EntityCallBack<BaseResponseBean<ChangeShiftEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<ChangeShiftEntity>>
                        (new TypeToken<BaseResponseBean<ChangeShiftEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<ChangeShiftEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                            showConfirmDialog("提交成功");
                            mMaterialBoxBindingAdapter.getData().clear();
                            mMaterialBoxBindingAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<ChangeShiftEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(),"TRANSFERMES");

                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE", "BIND");
                List<ChangeShiftEntity.ChangeShift> mdata = new ArrayList<>();
                Map<String, String> nameToValueMap = new HashMap<>();
                Map<String, List<ChangeShiftEntity.ChangeShift>> nameToEntitiesMap = new HashMap<>();
                for (ChangeShiftEntity.ChangeShift data : mMaterialBoxBindingAdapter.getData()){
                    if (!nameToEntitiesMap.containsKey(data.getLOTID())) {
                        nameToEntitiesMap.put(data.getLOTID(), new ArrayList<ChangeShiftEntity.ChangeShift>());
                    }
                    nameToEntitiesMap.get(data.getLOTID()).add(data);
                }
                List<MerterialBoxBindingEntity> merterialBoxBindingEntityList = new ArrayList<>();
                // 检查重复LotID
                for (Map.Entry<String, List<ChangeShiftEntity.ChangeShift>> entry : nameToEntitiesMap.entrySet()) {
                    if (entry.getValue().size() > 0) {
                        StringBuilder details = new StringBuilder();
                        for (ChangeShiftEntity.ChangeShift entity : entry.getValue()) {
                            details.append(entity.getMATERIALBOX()).append(",");
                        }
                        // 移除末尾的逗号和空格
                        String joinedDetails = details.substring(0, details.length() - 1);
                        nameToValueMap.put(entry.getKey(), joinedDetails);
                    }
                }

                for (Map.Entry<String, String> entry1 : nameToValueMap.entrySet()){
                    String[]  durableList= entry1.getValue().split(",");
                    MerterialBoxBindingEntity merterialBoxBindingEntity = new MerterialBoxBindingEntity();
                    merterialBoxBindingEntity.setLOTID(entry1.getKey());
                    merterialBoxBindingEntity.setDURABLELIST(durableList);
                    merterialBoxBindingEntityList.add(merterialBoxBindingEntity);
                }
                map.add("BINDLIST",new JsonParser().parse(new Gson().toJson(merterialBoxBindingEntityList)).getAsJsonArray());
                NetUtils.requestPostNet("CPC.BINDCARRIER","TRANSFERMES",this,map,callBack);
                break;
            case R.id.list_btn:
                if (mMaterialBoxBindingAdapter.deleteData.size() <= 0) {
                    showToast("请勾选批次后，在进行删除操作", false);
                    return;
                }
                for (ChangeShiftEntity.ChangeShift data : mMaterialBoxBindingAdapter.deleteData){
                    Iterator<ChangeShiftEntity.ChangeShift> iterator = mMaterialBoxBindingAdapter.getData().iterator();
                    while (iterator.hasNext()){
                        if (iterator.next().equals(data)) {
                            iterator.remove();
                        }
                    }
                }
                mMaterialBoxBindingAdapter.notifyDataSetChanged();
                break;
            case R.id.tvClear:
                mMaterialBoxBindingAdapter.getData().clear();
                mMaterialBoxBindingAdapter.notifyDataSetChanged();
                clearContent();
                break;

        }
    }

    //初始化页面
    private void clearContent() {
        etLot.setText("");
        etMaterialBox.setText("");
    }
}
